package net.mingsoft.flk.util;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

@Slf4j
public class FlkUtils {

    private static String Env;

    private static final String CONTENT = "content";
    private static final String CODE = "code";
    private static final String RESULT = "result";


    @Value("${spring.profiles.active}")
    public static void setEnv(String env) {
        Env = env;
    }

    public static String hmacSm3Msg(String content) {
        if (!"prod".equals(Env)) {
            return SecureUtil.md5(content);
        }
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(CONTENT, content);

            log.info("FlkUtils|decrypt|req|jsonObject={},", jsonObject);
            String s = HttpUtil.sendPost("http://10.1.3.49:7080/api/incident-server/incident/common/hmacSm3Msg", jsonObject.toJSONString());
            log.info("FlkUtils|decrypt|resp|content={}", s);
            JSONObject json = JSONObject.parseObject(s);
            if (json.getInteger(CODE) == 200) {
                return json.getString(RESULT);
            } else {
                return "";
            }

        } catch (Exception e) {
            log.error("FlkUtils|decrypt|error={}", e.getMessage());
            return "";
        }
    }


    public static boolean verification(String content, String encryptionKey) {
        if (!"prod".equals(Env)) {
            return SecureUtil.md5(content).equals(encryptionKey);
        }
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("content", content);
            jsonObject.put("encContent", encryptionKey);

            log.info("FlkUtils|decrypt|req|jsonObject={},", jsonObject);
            String s = HttpUtil.sendPost("http://10.1.3.49:7080/api/incident-server/incident/common/verifyHmacSm3Msg", jsonObject.toJSONString());
            log.info("FlkUtils|decrypt|resp|content={}", s);
            JSONObject json = JSONObject.parseObject(s);
            return json.getInteger(CODE) == 200;
        } catch (Exception e) {
            log.error("FlkUtils|decrypt|error={}", e.getMessage());
            return false;
        }
    }
}
